﻿namespace IBTrader.Modules.DailyTickData
{
    using IBTrader.Model;
    using IBTrader.Modules.Configuration;
    using IBTrader.Properties;
    using NLog;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    public abstract class TickBase
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        protected readonly Dictionary<int, Item> items = new Dictionary<int, Item>();
        private readonly Store store;
        public TickBase(Store store)
        {
            this.store = store;
        }
        protected abstract Item CreateItem(string symbol);
        protected bool Add(int id)
        {
            if (items.ContainsKey(id)) return true;
            var symbol = store.Contracts.Single(c => c.Id == id).Symbol;
            logger.Debug("{0} {1}", id, symbol);
            items.Add(id, CreateItem(symbol));
            return true;
        }
        public void Finish(object _, EventArgs __)
        {
            foreach (var key in items.Keys)
                items[key].Close();
            items.Clear();
        }
        protected abstract class Item
        {
            private static readonly Logger logger = LogManager.GetCurrentClassLogger();
            private readonly string symbol;
            private StreamWriter writer = null;
            private DateTime date;
            private int count;
            private string fileName;
            protected Item(string symbol)
            {
                this.symbol = symbol;
                Open();
            }
            protected void Write(params object[] args)
            {
                if (writer == null) return; // in case of close, not thread save
                if (date != Times.Now.Date)
                {
                    Close();
                    Open();
                }
                writer.WriteLine(string.Join(";", new object[] { ++count, Times.Now.ToString(Times.DateTimeFormat) }.Concat(args)));

            }
            protected virtual void Open()
            {
                date = Times.Now.Date;
                count = 0;
                var folder = Settings.Default.BacklogFolder;
                if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
                fileName = string.Format("{0} {1:" + Times.DateFormat + "}.txt", symbol, date);
                var filePath = Path.Combine(folder, fileName);
                writer = new StreamWriter(File.Open(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
                logger.Debug(fileName);
            }
            internal void Close()
            {
                writer.Close();
                writer = null;
                logger.Debug(fileName);
            }
        }
    }
}